package com.wizinno.android.urineflow.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import cn.hutool.core.collection.CollectionUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.wizinno.android.urineflow.R;
import com.wizinno.android.urineflow.activity.MainActivity;
import com.wizinno.android.urineflow.constant.CommonControl;
import com.wizinno.android.urineflow.constant.FragmentNoConstant;
import com.wizinno.android.urineflow.serialport.SerialPortUtil;

import java.util.ArrayList;
import java.util.List;

public class CheckingLeftFragment extends BaseFragment {
    private LineChart lc;
    private static final int COLOR_VOL = Color.parseColor("#fe9701");
    private static final int COLOR_RATE = Color.parseColor("#829bff");

    private TextView tv_checking_vol;
    private TextView tv_checking_rate;

    public CheckingLeftFragment() {
        setNo(FragmentNoConstant.CHECKING_LEFT);
    }

    private List<Float> weightList = new ArrayList<>();
    private List<Float> rateList = new ArrayList<>();
    private List<String> xLabelList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initData() {
        weightList.add(0f);
        rateList.add(0f);
        xLabelList.add("0");
        drawLine(weightList, rateList, xLabelList);
        //检查通讯是否正常
        if (CommonControl.INSTANCE.isUsbNormal) {
            //开始采集数据
            SerialPortUtil.startWeight();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_checking_left, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        lc = view.findViewById(R.id.lc);
        tv_checking_vol = view.findViewById(R.id.tv_checking_vol);
        tv_checking_rate = view.findViewById(R.id.tv_checking_rate);
    }

    /**
     * 处理USB串口上传的称重数据
     *
     * @param receiveBytes
     */
    public void handleWeightData(byte[] receiveBytes) {
        float weight = SerialPortUtil.transWeight(receiveBytes);
//        if(weight < 0){
//            weight = 0;
//        }
        weightList.add(weight);
        float rate;
        //采样频率-每秒5次
        int frequency = 5;
        int size = weightList.size();
        if (size == 1) {
            rate = weightList.get(0) * frequency;
        } else {
            rate = (weightList.get(size - 1) - weightList.get(size - 2)) * frequency;
        }
        rateList.add(rate);
        String label = String.format("%.1f", 0.2 * (size - 1));
        String[] labelSplit = label.split("\\.");
        if ("0".equals(labelSplit[1])) {
            label = labelSplit[0];
        }
        xLabelList.add(label);

        //更新统计数据
        tv_checking_vol.setText((int) weight + " ml");
        tv_checking_rate.setText((int) rate + " ml/s");

        drawLine(weightList, rateList, xLabelList);
        MainActivity.weightList = weightList;
        MainActivity.rateList = rateList;
    }


    private void drawLine(List<Float> volList, List<Float> rateList, List<String> xLabels) {
        int textSize = 20;
        List<Entry> volEntryList = new ArrayList<>();
        List<Entry> rateEntryList = new ArrayList<>();

        Description description = lc.getDescription();
        description.setText("");
        Legend legend = lc.getLegend();
        legend.setTextSize(textSize);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setForm(Legend.LegendForm.CIRCLE);
        legend.setFormSize(textSize);
        if (CollectionUtil.isNotEmpty(volList)) {
            for (int i = 0; i < volList.size(); i++) {
                volEntryList.add(new Entry(i, volList.get(i)));
            }
        }
        if (CollectionUtil.isNotEmpty(rateList)) {
            for (int i = 0; i < rateList.size(); i++) {
                rateEntryList.add(new Entry(i, rateList.get(i)));
            }
        }
        LineDataSet volSet = new LineDataSet(volEntryList, "尿流量(ml)");
        volSet.setLineWidth(2);//折线的宽度
        volSet.setCircleRadius(1);//数据点的半径
        volSet.setCircleColor(COLOR_VOL);//数据点的颜色
        volSet.setDrawFilled(false);//是否对数据点圆心进行填充
        volSet.setDrawCircleHole(false);//数据点圆是否为空心圆
        volSet.setColor(COLOR_VOL);//设置折线颜色
        volSet.setAxisDependency(YAxis.AxisDependency.LEFT);

        LineDataSet rateSet = new LineDataSet(rateEntryList, "尿流率(ml/s)");
        rateSet.setLineWidth(2);
        rateSet.setCircleRadius(1);
        rateSet.setCircleColor(COLOR_RATE);
        rateSet.setDrawFilled(false);
        rateSet.setDrawCircleHole(false);
        rateSet.setColor(COLOR_RATE);
        rateSet.setAxisDependency(YAxis.AxisDependency.RIGHT);

        LineData data = new LineData(volSet, rateSet);
        data.setDrawValues(false);//折线上是否绘制数据

        int yLabelCount = 9;

        //左边y轴
        YAxis leftAxis = lc.getAxisLeft();
        leftAxis.setTextColor(COLOR_VOL);
        leftAxis.setTextSize(textSize);
        leftAxis.setAxisMinimum(0);
        leftAxis.setDrawGridLines(true);
        leftAxis.setGridColor(Color.parseColor("#1088ff"));
        leftAxis.setLabelCount(yLabelCount);
        leftAxis.enableGridDashedLine(5, 2, 0);

        //右边y轴
        YAxis rightAxis = lc.getAxisRight();
        rightAxis.setTextColor(COLOR_RATE);
        rightAxis.setTextSize(textSize);
        rightAxis.setAxisMinimum(0);
        rightAxis.setDrawGridLines(false);
        rightAxis.setLabelCount(yLabelCount);


        XAxis xAxis = lc.getXAxis();//初始化X轴
        xAxis.setEnabled(true);//是否调用x轴
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴的位置
        xAxis.setTextSize(textSize);//设置标签的字体大小
        xAxis.setTextColor(Color.BLACK);//设置标签字体的颜色
        xAxis.setDrawAxisLine(true);//是否绘制x轴的直线
        xAxis.setDrawGridLines(false);//是否画网格线
        xAxis.setValueFormatter(new IndexAxisValueFormatter(xLabels));
        xAxis.setGranularity(5);

        //底部偏移量
        lc.setExtraBottomOffset(5);
        lc.setData(data);
        lc.invalidate();
    }

}